/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.aop;

import cn.easyplatform.lang.Lang;

/**
 * 一个默认的类加载器
 * 
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a>
 */
public class DefaultClassDefiner extends ClassLoader implements ClassDefiner {

	public DefaultClassDefiner(ClassLoader parent) {
		super(parent);
	}

	public Class<?> define(String className, byte[] bytes)
			throws ClassFormatError {
		try {
			return load(className);
		} catch (ClassNotFoundException e) {
		}
		// If not found ...
		return defineClass(className, bytes, 0, bytes.length);
	}

	public boolean has(String className) {
		try {
			load(className);
			return true;
		} catch (ClassNotFoundException e) {
		}
		return false;
	}

	public Class<?> load(String className) throws ClassNotFoundException {
		try {
			return Lang.loadClass(className);
		} catch (ClassNotFoundException e) {
			try {
				return ClassLoader.getSystemClassLoader().loadClass(className);
			} catch (ClassNotFoundException e2) {
				try {
					return getParent().loadClass(className);
				} catch (ClassNotFoundException e3) {
				}
			} catch (SecurityException e2) {// Fix for GAE 1.3.7, Fix issue 296
				try {
					return getParent().loadClass(className);
				} catch (ClassNotFoundException e3) {
				}
			}
		}
		return super.loadClass(className);
	}
}
